using System;
using System.Web;
using System.Xml;
using miPics.Common;


namespace miPics.Rss
{

	public class WriteRss
	{
		private HttpRequest CurrentRequest;

		// constructor
		public WriteRss(HttpRequest InputRequest)
		{
			this.CurrentRequest = InputRequest;
		}

		public void SaveRss()
		{
			string GalleryUrl = Config.General.GalleryUrl;

			// get gallery data into datatable
			miPicsDataAccessTableAdapters.GalleryListTableAdapter GalleryListTableAdapter = new miPicsDataAccessTableAdapters.GalleryListTableAdapter();
			miPicsDataAccess.GalleryListDataTable Galleries = GalleryListTableAdapter.GetData(false);

			// create xml document
			XmlTextWriter RssFile = new XmlTextWriter(this.CurrentRequest.PhysicalApplicationPath + "Rss.xml", null);
			RssFile.Formatting = Formatting.Indented;
			RssFile.Indentation = 1;
			RssFile.IndentChar = '\t';

			RssFile.WriteStartDocument();

			RssFile.WriteStartElement("rss");
			RssFile.WriteAttributeString("version", "2.0");

			RssFile.WriteStartElement("channel");

			RssFile.WriteElementString("title", Config.Rss.Title);
			RssFile.WriteElementString("link", GalleryUrl);
			RssFile.WriteElementString("description", Config.Rss.Description);

			// write out gallery items to RSS feed
			foreach (miPicsDataAccess.GalleryListRow GalleryRow in Galleries)
			{
				string GalleryItemUrl = GalleryUrl + "Gallery/?id=" + GalleryRow.GalleryID;

				RssFile.WriteStartElement("item");
				
				RssFile.WriteElementString("title", GalleryRow.Name);
				RssFile.WriteElementString("description", GalleryRow.Description);
				RssFile.WriteElementString("pubDate", GalleryRow.GalleryDate.ToString("ddd, d MMM yyyy 00:00:00 zz00"));
				RssFile.WriteElementString("link", GalleryItemUrl);

				RssFile.WriteStartElement("guid");
				RssFile.WriteAttributeString("isPermaLink", "true");
				RssFile.WriteString(GalleryItemUrl);
				RssFile.WriteEndElement(); // close </guid>

				RssFile.WriteEndElement(); // close </item>
			}

			RssFile.WriteEndElement(); // close </channel>

			RssFile.WriteEndElement(); // close </rss>

			RssFile.WriteEndDocument();
			RssFile.Close();
		}
	}

}